import { NestMiddleware, Injectable } from '@nestjs/common';
import { Response, NextFunction } from 'express';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class ParseUserRoles implements NestMiddleware {
  constructor(
    private readonly jwtService: JwtService,
    private readonly configService: ConfigService,
  ) {}
  use(req: any, res: Response, next: NextFunction) {
    console.log(req.headers,'req.headers');
    
    if (!req.headers.authorization) {
      res.status(401).send('请登录!');
    }
    const token = req.headers.authorization.split('Bearer ')[1];
    const decoded = this.jwtService.verify(token, {
      secret: this.configService.get<string>('SECRET_KEY'),
    });
    req.roles = decoded.roles;
    next();
  }
}
